package com.example.contacts;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Date;
import java.util.ArrayList;
import java.util.List;

import com.example.contacts.DB.DBTool;
import com.example.contacts.sql_bean.People;
import com.example.contacts.ListViewAdapter;
import com.example.contacts.ItemData;
import com.example.contacts.AddActivity;

import android.R.integer;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends Activity {
	
	EditText editText;
	ImageButton addButton;
	ImageButton queryButton;
	ListView listView;

	final static String DB_NAME="people.sqlite";
	final static String TABLE_NAME="people";

	ApplicationInfo applicationInfo;
	String packageName;
	String databasePath;

	DBTool dbTool;
	List<ItemData> data ;
	
	private void query_allpeople(){
		
    	data = new ArrayList<ItemData>();  	
    	Cursor cursor=dbTool.getPeople();
		if (cursor!=null) {
			//读取所有纪录
			List<People> peoples =new ArrayList<People>();
			while(cursor.moveToNext()){
				People p=new People();
				p.setId(cursor.getInt(0));
				p.setName(cursor.getString(1));
				p.setNumber(cursor.getString(2));
				p.setNote(cursor.getString(3));
				peoples.add(p);
			}
//			String info="";
			for(People people:peoples){
				ItemData data1= new ItemData();
				data1.setText1(people.getName());
				data1.setText2(people.getNumber());
				data.add(data1);
			}		
		}
		ListViewAdapter adapter = new ListViewAdapter(MainActivity.this, data);
    	listView.setAdapter(adapter);
	}
	
	OnClickListener listener=new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
			case R.id.imageButton_add:
				Intent intent=new Intent(MainActivity.this,AddActivity.class);
				startActivityForResult(intent, 1);
				break;
			case R.id.imageButton_query:
				ListView listView=(ListView)findViewById(R.id.listView1);
		    	data = new ArrayList<ItemData>();  	
		    	Cursor cursor=dbTool.getPeople(editText.getText().toString());
				if (cursor!=null) {
					//读取所有纪录
					List<People> peoples =new ArrayList<People>();
					while(cursor.moveToNext()){
						People p=new People();
						p.setId(cursor.getInt(0));
						p.setName(cursor.getString(1));
						p.setNumber(cursor.getString(2));
						p.setNote(cursor.getString(3));
						peoples.add(p);
					}
//					String info="";
					for(People people:peoples){
						ItemData data1= new ItemData();
						data1.setText1(people.getName());
						data1.setText2(people.getNumber());
						data.add(data1);
					}		
				}
				ListViewAdapter adapter = new ListViewAdapter(MainActivity.this, data);
		    	listView.setAdapter(adapter);
				break;
			default:
				break;
			}
			
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		initDatabase();  
		
		dbTool=new DBTool(databasePath);
		dbTool.openDatabase();
        init();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		dbTool.closeDatabase();
	}
	
	private void init(){
		
		editText=(EditText)findViewById(R.id.editText_query);
		addButton=(ImageButton)findViewById(R.id.imageButton_add);
		queryButton=(ImageButton)findViewById(R.id.imageButton_query);
		
		addButton.setOnClickListener(listener);
		queryButton.setOnClickListener(listener);
		
		editText.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// TODO Auto-generated method stub
				ListView listView=(ListView)findViewById(R.id.listView1);
		    	data = new ArrayList<ItemData>();  	
		    	Cursor cursor=dbTool.getPeople(editText.getText().toString());
				if (cursor!=null) {
					//读取所有纪录
					List<People> peoples =new ArrayList<People>();
					while(cursor.moveToNext()){
						People p=new People();
						p.setId(cursor.getInt(0));
						p.setName(cursor.getString(1));
						p.setNumber(cursor.getString(2));
						p.setNote(cursor.getString(3));
						peoples.add(p);
					}
//					String info="";
					for(People people:peoples){
						ItemData data1= new ItemData();
						data1.setText1(people.getName());
						data1.setText2(people.getNumber());
						data.add(data1);
					}		
				}
				ListViewAdapter adapter = new ListViewAdapter(MainActivity.this, data);
		    	listView.setAdapter(adapter);
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				
			}
		});
		
		listView=(ListView)findViewById(R.id.listView1);
		data = new ArrayList<ItemData>();  	
    	Cursor cursor=dbTool.getPeople();
		if (cursor!=null) {
			//读取所有纪录
			List<People> peoples =new ArrayList<People>();
			while(cursor.moveToNext()){
				People p=new People();
				p.setId(cursor.getInt(0));
				p.setName(cursor.getString(1));
				p.setNumber(cursor.getString(2));
				p.setNote(cursor.getString(3));
				peoples.add(p);
			}
//			String info="";
			for(People people:peoples){
				ItemData data1= new ItemData();
				data1.setText1(people.getName());
				data1.setText2(people.getNumber());
				data.add(data1);
			}		
		}
		ListViewAdapter adapter = new ListViewAdapter(MainActivity.this, data);
    	listView.setAdapter(adapter);
    	
    	listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
            	ItemData itemData=data.get(position);
				Cursor cursor=dbTool.getPeople(itemData.getText1(),itemData.getText2());
				People p=new People();
				if (cursor!=null) {
					while(cursor.moveToNext()){
						p.setId(cursor.getInt(0));
						p.setName(cursor.getString(1));
						p.setNumber(cursor.getString(2));
						p.setNote(cursor.getString(3));
					}		
				}								
				Intent intent=new Intent(MainActivity.this,InfoActivity.class);
				intent.putExtra("infoname", p.getName());
				intent.putExtra("infonumber", p.getNumber());
				intent.putExtra("infonote", p.getNote());
				startActivity(intent);
			}
		});
    	
    	listView.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
            	final ItemData itemData=data.get(position);
		                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
		                builder.setIcon(R.drawable.ic_launcher);
		                builder.setTitle("选择需要的操作");
		                //    指定下拉列表的显示数据
		                final String[] cities = {"拨打电话", "编辑", "删除"};
		                //    设置一个下拉的列表选择项
		                builder.setItems(cities, new DialogInterface.OnClickListener()
		                {
		                    @Override
		                    public void onClick(DialogInterface dialog, int which)
		                    {
		                        switch (which) {
								case 0:
									Intent intent=new Intent(Intent.ACTION_CALL);
									Uri phoneNumber=Uri.parse("tel:"+itemData.getText2().toString());
									intent.setData(phoneNumber);
									startActivity(intent);
									break;
								case 1:
									Cursor cursor=dbTool.getPeople(itemData.getText1(),itemData.getText2());
									People p=new People();
									if (cursor!=null) {
										while(cursor.moveToNext()){
											p.setId(cursor.getInt(0));
											p.setName(cursor.getString(1));
											p.setNumber(cursor.getString(2));
											p.setNote(cursor.getString(3));
										}		
									}								
									Intent intent2=new Intent(MainActivity.this,UpdateActivity.class);
									intent2.putExtra("id", String.valueOf(p.getId()));
									intent2.putExtra("oldname", p.getName());
									intent2.putExtra("oldnumber", p.getNumber());
									intent2.putExtra("oldnote", p.getNote());
									startActivityForResult(intent2, 2);
									break;
								case 2:{
									new AlertDialog.Builder(MainActivity.this).setTitle("删除提示框").setMessage("确认删除该数据？")
									.setPositiveButton("确定", new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog, int which) {
										long rows=dbTool.removePeople(itemData.getText1(),itemData.getText2());
										if(rows>0){
											Toast.makeText(MainActivity.this, "sucessful", Toast.LENGTH_SHORT).show();
											query_allpeople();
										}
									}})
									.setNegativeButton("取消",null)
									.show();
								}									
									break;

								default:
									break;
								}
		                    }
		                });
		                builder.show();
				return true;
			}
		});

	}


	private void initDatabase(){
		packageName=getPackageName();
		try {
			applicationInfo=getPackageManager().getApplicationInfo(packageName, PackageManager.GET_META_DATA);
			String databaseDir=applicationInfo.dataDir+File.separator+"database";
			databasePath=databaseDir+File.separator+DB_NAME;
			//Toast.makeText(MainActivity.this, databasePath, Toast.LENGTH_SHORT).show();
			//准备创建数据库目录
			File dbDir=new File(databaseDir);
			if(!dbDir.exists()){
				dbDir.mkdir();
			}

			//复制数据库文件到 databases目录下
			InputStream inputStream=getAssets().open("people.sqlite");
			File dbFile=new File(databasePath);
			if(!dbFile.exists()){
				dbFile.createNewFile();
				//读取文件（assets/people.sqlite）				
				//写入到databasepath
				FileOutputStream fos=new FileOutputStream(dbFile);
				//读取数据缓存
				byte[] buffer= new byte[1024];
				//实际读取文件的字节数
				int count=0;

				while((count=inputStream.read(buffer))!=-1){
					fos.write(buffer, 0, count);
				}
				fos.close();
				inputStream.close();
			}
		} catch (NameNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    	// TODO Auto-generated method stub
    	//4 
    	switch (requestCode) {
		case 1:{
			switch (resultCode) {
			case RESULT_OK:
				People people=new People();
				people.setName(data.getStringExtra("addname"));
				people.setNumber(data.getStringExtra("addnumber"));
				people.setNote(data.getStringExtra("addnote"));
				long rows=dbTool.addPeople(people);
				if(rows>0){
					Toast.makeText(MainActivity.this, "sucessful", Toast.LENGTH_SHORT).show();
				}
				query_allpeople();
				break;
			case RESULT_CANCELED:
				Toast.makeText(MainActivity.this, "cancel ok", Toast.LENGTH_SHORT).show();
				break;

			default:
				break;
			}
		}
		
			break;
		case 2:
		{
			switch (resultCode) {
			case RESULT_OK:
				People people=new People();
				people.setId(Integer.parseInt(data.getStringExtra("newid")));
				people.setName(data.getStringExtra("newname"));
				people.setNumber(data.getStringExtra("newnumber"));
				people.setNote(data.getStringExtra("newnote"));
				System.out.println(people.getId());
				long rows=dbTool.updatePeople(people);
				if(rows>0){
					Toast.makeText(MainActivity.this, "sucessful", Toast.LENGTH_SHORT).show();
				}
				query_allpeople();
				break;
			case RESULT_CANCELED:
				Toast.makeText(MainActivity.this, "cancel ok", Toast.LENGTH_SHORT).show();
				break;

			default:
				break;
		}
		}
			break;
			

		default:
			break;
			
		}
    	super.onActivityResult(requestCode, resultCode, data);
    }
	
}
